<template>
  <div class="ui-tree w-full">
    <el-input
      v-if="getExtension.openSearch && getExtension.openSearch.value"
      v-model.trim="filterContent"
      clearable
      :placeholder="translateTitle('Ve.elements.请输入查询条件')"
      size="mini"
    />
    <el-tree
      :ref="info._id"
      v-ui-ref="vSetRef"
      :accordion="accordion"
      :current-node-key="currentNodeKey"
      :data="treeData"
      :expand-on-click-node="getExtension.clickExpandNode ? !getExtension.clickExpandNode.value : true"
      :filter-node-method="filterNode"
      highlight-current
      :node-key="getExtension.idField.value"
      :props="defaultProps"
      :show-checkbox="getExtension.isCheckModel && getExtension.isCheckModel.value"
      @check-change="handleCheckChange"
      @dblclick="onDbClick"
      @node-click="handleNodeClick"
      @node-collapse="updateHeight"
      @node-expand="updateHeight"
    />
    <!-- <template #default="{ node }">
        <span class="custom-tree-node">
          <vui-icon v-if="info.extension.icon.value" :icon="info.extension.icon.value" />
          <span>{{ node.label }}</span>
        </span>
      </template> -->
    <!-- </el-tree> -->
  </div>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import isEmpty from 'lodash/isEmpty'
  import isArray from 'lodash/isArray'
  import merge from 'lodash/merge'
  import trim from 'lodash/trim'
  import { defineComponent } from 'vue'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
  import { UiMixin, RefsInjectMixin } from '@ve/mixin'
  import cloneDeep from 'lodash/cloneDeep'

  export default defineComponent({
    name: 'UiTree',
    components: {},
    mixins: [UiMixin, RefsInjectMixin],
    props: {},
    data() {
      return {
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label',
        },
        lvField: '',
        parentIdField: '',
        activeData: {}, // 选中的数据
        filterContent: '',
        currentNodeKey: null,
      }
    },
    computed: {
      accordion() {
        return this.info.extension.accordion.value
      },
      getData() {
        return this.info.data.requestData?.data || []
      },
      getInfo() {
        return this.info
      },
      getExtension() {
        return this.info.extension
      },
    },
    watch: {
      getData: {
        // deep: true,
        immediate: true,
        handler: function (newval) {
          if (newval) {
            this.treeData = this.clearUp(newval)
            // 默认选中
            this.setDefaultState()
          }
        },
      },
      filterContent(val) {
        this.runFilterNode(val)
      },
    },
    mounted() {
      console.warn('info', this.info)
      // 读取props配置
      this.defaultProps.label = this.getExtension.label.value
      // this.defaultProps.children = this.getExtension.children.value
      this.lvField = this.getExtension.lvField ? this.getExtension.lvField.value : 'lv'
      this.parentIdField = this.getExtension.parentIdField ? this.getExtension.parentIdField.value : 'parentId'
      if (this.getExtension.isCheckModel && this.getExtension.isCheckModel.value) {
        // 如果是多选模式 则选中数据为数组形式
        this.activeData = []
      }
      // 调用接口
      if (this.getInfo.extension.api.value) this.requestData()
    },
    methods: {
      translateTitle,
      handleCheckChange(data, isChecked) {
        const idField = this.getExtension.idField.value
        const lvField = this.getExtension.lvField.value
        const parentIdField = this.getExtension.parentIdField.value
        if (isChecked) {
          // 如果是激活 则添加数据
          const dataObj = {
            [idField]: data[idField],
            [lvField]: data[lvField],
            [parentIdField]: data[parentIdField],
          }
          // 添加需要额外获取的值
          if (this.getExtension.getOtherDataKey) {
            const getDataKeyList = this.getExtension.getOtherDataKey.value ? this.getExtension.getOtherDataKey.value.split(',') : []
            getDataKeyList.forEach((item) => {
              const dataKey = trim(item)
              dataObj[dataKey] = data[dataKey]
            })
          }

          this.activeData.push(dataObj)
        } else {
          this.activeData = this.activeData.filter((item) => {
            return item[idField] !== data[idField]
          })
        }
      },
      handleNodeClick(nodeProp) {
        // console.log('nodeProp --------- ', nodeProp)
        // 由于 element 的 tree 组件阻止了默认的点击事件 所以通过以下方法触发配置时选择组件方法
        this.$parent.$parent.selectCommand && this.$parent.$parent.selectCommand(this.info)
        // 不是多选模式的话 则赋值
        if (!(this.getExtension.isCheckModel && this.getExtension.isCheckModel.value)) {
          const idField = this.getExtension.idField.value
          const lvField = this.getExtension.lvField.value
          const parentIdField = this.getExtension.parentIdField.value
          // this.activeData = { ...cloneDeep(nodeProp) }
          this.activeData[idField] = nodeProp[idField]
          this.activeData[lvField] = nodeProp[lvField]
          this.activeData[parentIdField] = nodeProp[parentIdField]
          // 添加需要额外获取的值
          if (this.getExtension.getOtherDataKey) {
            const getDataKeyList = this.getExtension.getOtherDataKey.value ? this.getExtension.getOtherDataKey.value.split(',') : []
            getDataKeyList.forEach((item) => {
              const dataKey = trim(item)
              this.activeData[dataKey] = nodeProp[dataKey]
            })
          }
        }

        // this.info.extension.idField.value && (this.info.data.formData.treeData = nodeProp[this.info.extension.idField.value])
        // 调用点击事件
        this.onClick()
      },
      requestData(cb) {
        let requestDataObj = {}
        isArray(this.info.extension.requestData.value) &&
          this.info.extension.requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(item.value)) {
              itemVal = replaseRegVariable(itemVal, this.info.data.formData)
            }
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
        let options = {
          api: this.info.extension.api.value,
          method: this.info.extension.method.value,
          getDataKey: this.info.extension.getDataKey.value,
          data: merge(requestDataObj, this.info.data.formData),
        }
        if (!trim(options.api)) return
        this.request(options, cb)
      },
      // 统一请求
      request(options = {}, cb) {
        this.loading = true
        let getDataKey = this.getExtension.getDataKey.value
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(options.data),
            method: options.method,
          },
        }).then((res) => {
          this.loading = false
          //解密
          // console.log(decryptd(res))
          // let _requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          // if (isArray(_requestData)) {
          //   this.getInfo.data.requestData = _requestData
          // } else {
          //   this.getInfo.data.requestData = []
          // }
          this.getInfo.data.requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          // 回调
          cb && cb(res)
        })
      },
      lookForParent(parentList, childrenItem) {
        parentList.forEach((pItem) => {
          if (pItem[this.getExtension.idField.value] === childrenItem[this.getExtension.parentIdField.value]) {
            pItem.children ? pItem.children.push(childrenItem) : (pItem.children = [childrenItem])
            // if (pItem.children) {
            //   pItem.children.push(item)
            // } else {

            // }
          } else {
            pItem.children ? this.lookForParent(pItem.children, childrenItem) : ''
          }
        })
      },
      clearUp(dataList) {
        const newDataList = cloneDeep(dataList)
        newDataList.forEach((r) => {
          delete r.children
        })
        const orderlyData = newDataList.sort((a, b) => {
          return a[this.lvField] - b[this.lvField]
        })
        let obj = []
        orderlyData.map((item) => {
          if (item[this.lvField] === 1) {
            obj.push(item)
          } else {
            this.lookForParent(obj, item)
          }
        })
        console.log('obj ------------ ', obj)
        return obj
      },
      $getActiveData() {
        return {
          [this.getExtension.model.value]: this.activeData,
        }
      },
      filterNode(value, data) {
        if (!value) return true
        return data[this.defaultProps.label].includes(value)
      },
      // 触发树组件的筛选
      runFilterNode(val) {
        this.$refs[this.info._id].filter(val)
      },
      // 清除激活值
      clearActiveValue() {
        if (this.getExtension.isCheckModel && this.getExtension.isCheckModel.value) {
          // 如果是多选模式 则选中数据为数组形式
          this.activeData = []
        } else {
          this.activeData = {}
        }
      },
      // 设置默认状态
      setDefaultState() {
        // 不是多选模式的话 则直接调用点击事件即可
        if (!(this.getExtension.isCheckModel && this.getExtension.isCheckModel.value)) {
          if (isEmpty(this.activeData)) {
            // 如果激活值为空的话 则默认激活第一项
            this.treeData[0] && this.handleNodeClick(this.treeData[0])
          } else {
            this.handleNodeClick(this.activeData)
          }
          // 设置选中状态
          this.$nextTick(() => {
            if (!isEmpty(this.treeData)) {
              this.$refs[this.info._id] && this.$refs[this.info._id].setCurrentKey(this.activeData[this.getExtension.idField.value])
            }
          })
        } else {
          // 多选模式
          if (isEmpty(this.activeData)) {
            // 如果激活值为空的话 则默认激活第一项
            this.treeData[0] && this.handleNodeClick(this.treeData[0])
          } else {
            // 否则默认点击第一项
            this.handleNodeClick(this.activeData[0])
          }
          // 设置选中状态
          this.$nextTick(() => {
            if (!isEmpty(this.treeData)) {
              if (isEmpty(this.activeData)) {
                // 如果激活值为空的话 则默认激活第一项
                this.treeData[0] &&
                  this.$refs[this.info._id] &&
                  this.$refs[this.info._id].setCurrentKey(this.treeData[0][this.getExtension.idField.value])
              } else {
                // 否则默认点击第一项
                this.$refs[this.info._id] && this.$refs[this.info._id].setCurrentKey(this.activeData[0][this.getExtension.idField.value])
                this.activeData.forEach((item) => {
                  this.$refs[this.info._id] && this.$refs[this.info._id].setChecked(item[this.getExtension.idField.value], true, false)
                })
              }
            }
          })
        }
      },
      // 触发其他组件重新计算高度
      updateHeight() {
        // this.$pub(`SplitpaneResized_${this.previewPageId()}`, true)
      },
    },
  })
</script>
<style lang="scss" scoped>
  :deep() {
    .el-tree .is-current > .el-tree-node__content {
      background: #ecf5ff;
    }
  }
</style>
